package com.yuandianrrp.log.jdalog.job;

import com.yuandianrrp.log.jdalog.JdaLogContext;
import com.yuandianrrp.log.jdalog.utils.WeightLoginUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.helpers.FormattingTuple;
import org.slf4j.helpers.MessageFormatter;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;

/**
 * 文件逻辑
 *
 * @author Administrator
 */
public class JobLogger {

    private static Logger logger = LoggerFactory.getLogger("jda logger");

    /**
     * append log
     *
     * @param callInfo
     * @param appendLog
     * @param logFileName
     */
    private static void logDetail(StackTraceElement callInfo, String appendLog, String logFileName,String threadName) {


        String formatAppendLog = WeightLoginUtils.formatDateTime(new Date()) + " " +
                "[" + callInfo.getClassName() + "#" + callInfo.getMethodName() + "]" + "-" + "[" + callInfo.getLineNumber() + "]" + "-" + "[" + threadName + "]" + " " +
                (appendLog != null ? appendLog : "");
        logger.info(formatAppendLog);
        logFileName = logFileName+ "_" + JdaLogContext.getCurrentEnv() + "_" + WeightLoginUtils.formatCurrentDate() + ".log";
        if (logFileName.trim().length() > 0) {
            JobFileAppender.appendLog(logFileName, formatAppendLog);
        } else {
            logger.info(">>>>>>>>>>> {}", formatAppendLog);
        }
    }

    /**
     * append log with pattern
     *
     * @param appendLogPattern   like "aaa {} bbb {} ccc"
     * @param appendLogArguments like "111, true"
     */
    public static void log(StackTraceElement callInfo , String logFileName, String threadName, String appendLogPattern, Object... appendLogArguments) {
        FormattingTuple ft = MessageFormatter.arrayFormat(appendLogPattern, appendLogArguments);
        String appendLog = ft.getMessage();
        logDetail(callInfo, appendLog, logFileName,threadName);
    }

    /**
     * append exception stack
     *
     * @param e
     */
    public static void log(StackTraceElement callInfo , String logFileName, Throwable e, String threadName) {
        StringWriter stringWriter = new StringWriter();
        e.printStackTrace(new PrintWriter(stringWriter));
        String appendLog = stringWriter.toString();
        logDetail(callInfo, appendLog, logFileName, threadName);
    }

}
